#!/bin/bash

# Note : Make sure you place NOPASSWD in your /etc/sudoers or this script will annoy you (see jconfig -> fix stuff)

function usage() {
  echo usage : jfrpm output.rpm arch [files.lst]
  echo desc : creates RPM files from file.spec
  echo arch : any, x32, x64, a32, a64
  echo note : files.lst is appended to file.spec during process
  echo note : output.rpm is ignored \(for compatibility with other scripts\)
  exit
}

function error() {
  echo Error : $1
  exit
}

if [ "$1" = "" ]; then usage; fi
if [ "$2" = "" ]; then usage; fi
if [ "$1" = "--help" ]; then usage; fi
if [ "$1" = "-h" ]; then usage; fi

FILES=files.lst
if [ -f files-fedora.lst ]; then FILES=files-fedora.lst; fi
if [ ! "$3" = "" ]; then FILES=$3; fi

ARCH=$2
BITS=${ARCH:1:2}
if [ -f files-$BITS.lst ]; then FILES=files-$BITS.lst; fi

case $ARCH in
x32)
  ARCHEXT=i686
  ;;
x64)
  ARCHEXT=x86_64
  ;;
a32)
  ARCHEXT=armv7hl
  ;;
a64)
  ARCHEXT=aarch64
  ;;
*)
  echo Invalid arch!
  exit
  ;;
esac

TMPDIR=jfrpm.$RANDOM

java -cp /usr/share/java/javaforce.jar javaforce.utils.GenPkgInfo fedora $ARCH $FILES

WORKDIR=`pwd`
mkdir $TMPDIR

#build data.tar.bz2 (gz,bz2,lzma,others?)
if [ -f data.tar.bz2 ]; then rm -f data.tar.bz2; fi
tar cjf data.tar.bz2 -T $FILES

cat $FILES >> rpm.spec
cd $TMPDIR

if [ ! `pwd` = $WORKDIR/$TMPDIR ]; then error "failed to use temp folder $TMPDIR"; fi

sudo tar xjf ../data.tar.bz2
#NOTE:rpmbuild nukes the buildroot once complete, which is the current folder - be careful!!!
sudo rpmbuild -bb ../rpm.spec --buildroot `pwd`
cd ..
sudo rm -rf $TMPDIR
rm -f data.tar.bz2

rm rpm.spec

mv /root/rpmbuild/RPMS/$ARCHEXT/*.rpm .

echo Complete!
